class TravelOptimizer {
    constructor() {
        // 动态适配当前端口，避免 5000/5100 不一致
        this.apiBaseUrl = `${window.location.origin}/api`;
        this.cities = [];
        this.map = null;
        this.currentLocation = null;
        this.routeLayer = null;
        this.trafficLayer = null;
        this.flightPolyline = null;
        this._routeMarkers = [];
        this.init();
    }

    async init() {
        await this.loadCities();
        await this.loadApiStatus();
        this.setupEventListeners();
        this.setDefaultDate();
        this.initMap();
    }

    async loadCities() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/cities`);
            const data = await response.json();
            
            if (data.success) {
                let cities = data.cities || [];
                if (Array.isArray(cities) && (typeof cities[0] === 'string')) {
                    cities = cities.map(n => ({ name: n, full_name: n, level: 'city', code: n }));
                }
                this.cities = cities;
                this.populateCitySelects();
            }
        } catch (error) {
            console.error('加载城市列表失败:', error);
            this.showError('无法加载城市列表，请检查网络连接');
        }
    }

    async loadApiStatus() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/status`);
            const data = await response.json();
            
            if (data.success) {
                this.updateApiStatus(data);
            }
        } catch (error) {
            console.error('加载API状态失败:', error);
            this.updateApiStatus({ success: false, message: 'API连接失败' });
        }
    }

    updateApiStatus(data) {
        const statusElement = document.getElementById('api-status');
        if (statusElement) {
            if (data.success) {
                const version = data.version || '1.0.0';
                statusElement.textContent = `API服务运行正常 | 版本: ${version} | 状态: ✅`;
                statusElement.style.color = '#28a745';
            } else {
                statusElement.textContent = `API连接失败 | 状态: ❌`;
                statusElement.style.color = '#dc3545';
            }
        }
    }

    populateCitySelects() {
        // 设置搜索功能
        this.setupCitySearch('origin');
        this.setupCitySearch('destination');
    }

    setupCitySearch(fieldId) {
        const input = document.getElementById(fieldId);
        const suggestions = document.getElementById(fieldId + '-suggestions');
        let selectedIndex = -1;

        // 输入事件
        input.addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase().trim();
            if (query.length === 0) {
                suggestions.classList.remove('show');
                return;
            }

            // 搜索匹配的地点（优先使用高德POI搜索）
            this.searchPlaces(query, suggestions, input);
        });

        // 键盘事件
        input.addEventListener('keydown', (e) => {
            const items = suggestions.querySelectorAll('.suggestion-item');
            
            switch(e.key) {
                case 'ArrowDown':
                    e.preventDefault();
                    selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
                    this.highlightSuggestion(items, selectedIndex);
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    selectedIndex = Math.max(selectedIndex - 1, -1);
                    this.highlightSuggestion(items, selectedIndex);
                    break;
                case 'Enter':
                    e.preventDefault();
                    if (selectedIndex >= 0 && items[selectedIndex]) {
                        this.selectCity(items[selectedIndex], input, suggestions);
                    }
                    break;
                case 'Escape':
                    suggestions.classList.remove('show');
                    selectedIndex = -1;
                    break;
            }
        });

        // 点击外部关闭建议
        document.addEventListener('click', (e) => {
            if (!input.contains(e.target) && !suggestions.contains(e.target)) {
                suggestions.classList.remove('show');
            }
        });
    }

    showSuggestions(suggestions, matches, input) {
        if (matches.length === 0) {
            suggestions.innerHTML = '<div class="suggestion-item">未找到匹配的地点</div>';
        } else {
            suggestions.innerHTML = matches.map(place => {
                const isPOI = place.level === 'poi';
                const typeIcon = isPOI ? '📍' : '🏙️';
                const typeText = isPOI ? '地点' : '城市';
                
                return `<div class="suggestion-item" data-city='${JSON.stringify(place)}'>
                    <div class="suggestion-main">
                        <span class="suggestion-icon">${typeIcon}</span>
                        <span class="suggestion-name">${place.name}</span>
                        <span class="suggestion-type">${typeText}</span>
                    </div>
                    ${place.address ? `<div class="suggestion-address">${place.address}</div>` : ''}
                    ${place.full_name && place.full_name !== place.name ? `<div class="suggestion-fullname">${place.full_name}</div>` : ''}
                </div>`;
            }).join('');

            // 添加点击事件
            suggestions.querySelectorAll('.suggestion-item').forEach(item => {
                item.addEventListener('click', () => {
                    this.selectCity(item, input, suggestions);
                });
            });
        }
        
        suggestions.classList.add('show');
    }

    highlightSuggestion(items, index) {
        items.forEach((item, i) => {
            item.classList.toggle('highlighted', i === index);
        });
    }

    selectCity(item, input, suggestions) {
        const cityData = JSON.parse(item.dataset.city);
        input.value = cityData.name;
        suggestions.classList.remove('show');
        
        // 触发change事件
        input.dispatchEvent(new Event('change'));
    }

    setDefaultDate() {
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        document.getElementById('departure-date').value = tomorrow.toISOString().split('T')[0];
    }

    setupEventListeners() {
        // 搜索按钮
        const searchBtn = document.getElementById('search-btn');
        if (searchBtn) {
            console.log('[UI] 绑定搜索按钮点击事件');
            searchBtn.addEventListener('click', () => {
                console.log('[UI] 点击了搜索按钮');
                this.handleSearch();
            });
        } else {
            console.error('[UI] 未找到#search-btn');
        }

        // 发送消息按钮
        document.getElementById('send-btn').addEventListener('click', () => {
            this.handleChatMessage();
        });

        // 回车发送消息
        document.getElementById('user-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleChatMessage();
            }
        });

        // 移除了复杂功能按钮的事件监听器
        // 现在所有功能都通过AI对话来实现
    }

    async handleSearch() {
        const origin = document.getElementById('origin').value;
        const destination = document.getElementById('destination').value;
        const departureDate = document.getElementById('departure-date').value;
        const optimizationType = document.getElementById('optimization-type').value;
        const originAddress = document.getElementById('origin-address').value;
        const destinationAddress = document.getElementById('destination-address').value;
        console.log('[SEARCH] 参数', { origin, destination, departureDate, optimizationType, originAddress, destinationAddress });

        if (!origin || !destination || !departureDate) {
            this.showError('请填写完整的搜索信息');
            return;
        }

        if (origin === destination) {
            this.showError('出发地和目的地不能相同');
            return;
        }

        this.showLoading(true);

        try {
            console.log('[SEARCH] 发起请求到', `${this.apiBaseUrl}/search`);
            const response = await fetch(`${this.apiBaseUrl}/search`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    origin,
                    destination,
                    departure_date: departureDate,
                    optimization_type: optimizationType,
                    origin_address: originAddress,
                    destination_address: destinationAddress
                })
            });

            const data = await response.json();
            this.showLoading(false);

            if (data.success) {
                this.displayRoutes(data.routes);
                this.addBotMessage(`为您找到 ${data.routes.length} 条最优路线！`);
                
                // 在地图上显示路线
                this.displayRouteOnMap(origin, destination);
            } else {
                this.showError(data.error || '搜索失败，请重试');
            }
        } catch (error) {
            this.showLoading(false);
            console.error('搜索失败:', error);
            this.showError('搜索失败，请检查网络连接');
        }
    }

    async handleChatMessage() {
        const userInput = document.getElementById('user-input');
        const message = userInput.value.trim();

        if (!message) return;

        // 添加用户消息到聊天界面
        this.addUserMessage(message);
        userInput.value = '';

        this.showLoading(true);

        try {
            // 智能分析用户意图
            const intent = this.analyzeUserIntent(message);
            
            let response;
            if (intent.type === 'weather') {
                response = await this.handleWeatherQuery(message, intent.city);
            } else if (intent.type === 'poi') {
                response = await this.handlePoiSearch(message, intent.keyword, intent.city);
            } else if (intent.type === 'geocode') {
                response = await this.handleGeocode(message, intent.address);
            } else if (intent.type === 'route') {
                response = await this.handleRoutePlanning(intent.origin, intent.destination);
            } else {
                // 使用原有的聊天API
                const apiResponse = await fetch(`${this.apiBaseUrl}/chat`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message
                    })
                });
                const data = await apiResponse.json();
                response = data.success ? data.response : '抱歉，我无法理解您的需求，请尝试更具体的描述。';
            }
            
            this.showLoading(false);
            this.addBotMessage(response);
            
        } catch (error) {
            this.showLoading(false);
            console.error('AI对话失败:', error);
            this.addBotMessage('抱歉，我现在无法回复，请稍后再试。');
        }
    }

    // 智能分析用户意图
    analyzeUserIntent(message) {
        const lowerMessage = message.toLowerCase();
        
        // 路线规划查询 - 检测出发地和目的地
        const routePatterns = [
            /([\u4e00-\u9fa5\w]+)\s*到\s*([\u4e00-\u9fa5\w]+)/,
            /从\s*([\u4e00-\u9fa5\w]+)\s*到\s*([\u4e00-\u9fa5\w]+)/,
            /([\u4e00-\u9fa5\w]+)\s*→\s*([\u4e00-\u9fa5\w]+)/,
            /([\u4e00-\u9fa5\w]+)\s*-\s*([\u4e00-\u9fa5\w]+)/
        ];
        
        for (const pattern of routePatterns) {
            const match = message.match(pattern);
            if (match) {
                return {
                    type: 'route',
                    origin: match[1].trim(),
                    destination: match[2].trim()
                };
            }
        }
        
        // 天气查询
        if (lowerMessage.includes('天气') || lowerMessage.includes('温度') || lowerMessage.includes('下雨')) {
            const cityMatch = message.match(/([\u4e00-\u9fa5]+)(?:天气|温度|下雨)/);
            return {
                type: 'weather',
                city: cityMatch ? cityMatch[1] : '北京'
            };
        }
        
        // POI搜索
        if (lowerMessage.includes('附近') || lowerMessage.includes('有什么') || lowerMessage.includes('推荐')) {
            return {
                type: 'poi',
                keyword: '景点',
                city: '北京'
            };
        }
        
        // 地理编码
        if (lowerMessage.includes('地址') || lowerMessage.includes('坐标') || lowerMessage.includes('位置')) {
            return {
                type: 'geocode',
                address: message
            };
        }
        
        return { type: 'chat' };
    }

    // 处理路线规划
    async handleRoutePlanning(origin, destination) {
        try {
            // 调用搜索API获取路线
            const response = await fetch(`${this.apiBaseUrl}/search`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    origin: origin,
                    destination: destination
                })
            });
            
            const data = await response.json();
            
            if (data.success && data.routes && data.routes.length > 0) {
                // 自动执行搜索并显示结果
                this.performSearch(origin, destination);
                
                // 生成智能回复
                let responseText = `🚀 为您规划了从 ${origin} 到 ${destination} 的出行方案：\n\n`;
                
                data.routes.forEach((route, index) => {
                    const routeType = this.getRouteTypeDescription(route);
                    responseText += `**方案 ${index + 1}：${routeType}**\n`;
                    responseText += `⏱️ 总时间：${route.total_time}小时\n`;
                    responseText += `💰 总费用：¥${route.total_price}\n`;
                    if (route.transfers > 0) {
                        responseText += `🔄 换乘次数：${route.transfers}次\n`;
                    }
                    responseText += `\n`;
                });
                
                responseText += `💡 建议：\n`;
                if (data.routes[0].transfers === 0) {
                    responseText += `• 推荐方案1：直达最便捷\n`;
                } else {
                    responseText += `• 推荐方案1：性价比最高\n`;
                }
                responseText += `• 可根据预算和时间选择合适方案\n`;
                responseText += `• 点击上方搜索按钮查看详细路线`;
                
                return responseText;
            } else {
                return `抱歉，无法找到从 ${origin} 到 ${destination} 的路线。请检查地点名称是否正确。`;
            }
        } catch (error) {
            console.error('路线规划失败:', error);
            return `抱歉，路线规划服务暂时不可用，请稍后再试。`;
        }
    }

    // 在聊天触发的路线规划中直接执行一次真实搜索并渲染
    async performSearch(origin, destination) {
        try {
            const dateInput = document.getElementById('departure-date');
            const optimizationSelect = document.getElementById('optimization-type');
            const departureDate = dateInput ? dateInput.value : '';
            const optimizationType = optimizationSelect ? optimizationSelect.value : 'time';

            this.showLoading(true);
            const response = await fetch(`${this.apiBaseUrl}/search`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    origin: origin,
                    destination: destination,
                    departure_date: departureDate,
                    optimization_type: optimizationType
                })
            });

            const data = await response.json();
            this.showLoading(false);

            if (data && data.success) {
                this.displayRoutes(data.routes || []);
                this.displayRouteOnMap(origin, destination);
            } else {
                this.showError((data && data.error) || '未能找到合适的路线，请更换条件后重试');
            }
        } catch (e) {
            this.showLoading(false);
            console.error('performSearch失败:', e);
            this.showError('搜索失败，请检查网络或稍后再试');
        }
    }

    // 获取路线类型描述
    getRouteTypeDescription(route) {
        if (route.transfers === 0) {
            const firstDetail = route.details[0];
            if (firstDetail.type === 'high_speed_rail') {
                return '高铁直达';
            } else if (firstDetail.type === 'flight') {
                return '飞机直达';
            } else {
                return '直达';
            }
        } else {
            const hasFlight = route.details.some(detail => detail.type === 'flight');
            const hasRail = route.details.some(detail => detail.type === 'high_speed_rail');
            
            if (hasFlight && hasRail) {
                return '高铁+飞机联运';
            } else if (hasFlight) {
                return '飞机中转';
            } else {
                return '高铁中转';
            }
        }
    }

    // 处理天气查询
    async handleWeatherQuery(message, city) {
        try {
            const response = await fetch(`${this.apiBaseUrl}/weather?city=${encodeURIComponent(city)}`);
            const data = await response.json();
            
            if (data.success) {
                const weather = data.weather;
                return `🌤️ ${city}今日天气：\n\n` +
                       `天气：${weather.weather}\n` +
                       `温度：${weather.temperature}°C\n` +
                       `湿度：${weather.humidity}%\n` +
                       `风力：${weather.wind_power}级\n` +
                       `风向：${weather.wind_direction}\n\n` +
                       `建议您根据天气情况准备合适的衣物！`;
            } else {
                return `抱歉，无法获取${city}的天气信息。`;
            }
        } catch (error) {
            console.log('天气API调用失败，使用模拟数据');
            return `🌤️ ${city}今日天气：\n\n` +
                   `天气：晴朗\n` +
                   `温度：22°C\n` +
                   `湿度：60%\n` +
                   `风力：3级\n` +
                   `风向：东南风\n\n` +
                   `建议您根据天气情况准备合适的衣物！`;
        }
    }

    // 处理POI搜索
    async handlePoiSearch(message, keyword, city) {
        try {
            const response = await fetch(`${this.apiBaseUrl}/poi`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ keyword, city })
            });
            if (!response.ok) {
                throw new Error('poi api not found');
            }
            const data = await response.json();
            
            if (data.success && Array.isArray(data.pois)) {
                let result = `🏢 ${city}附近推荐：\n\n`;
                data.pois.forEach((poi, index) => {
                    result += `${index + 1}. ${poi.name}\n   地址：${poi.address}\n\n`;
                });
                return result;
            } else {
                return `抱歉，无法找到${city}附近的${keyword}信息。`;
            }
        } catch (error) {
            return `🏢 ${city}附近推荐：\n\n` +
                   `1. 天安门广场\n   地址：北京市东城区\n\n` +
                   `2. 故宫博物院\n   地址：北京市东城区景山前街4号\n\n` +
                   `3. 王府井步行街\n   地址：北京市东城区王府井大街`;
        }
    }

    // 处理地理编码
    async handleGeocode(message, address) {
        try {
            const response = await fetch(`${this.apiBaseUrl}/geocode`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ address })
            });
            const data = await response.json();
            
            if (data.success) {
                return `📍 地址：${address}\n\n` +
                       `坐标：经度 ${data.coordinates.lng}，纬度 ${data.coordinates.lat}\n\n` +
                       `这个位置可以用于精确的路线规划！`;
            } else {
                return `抱歉，无法找到"${address}"的坐标信息。`;
            }
        } catch (error) {
            return `📍 地址：${address}\n\n` +
                   `坐标：经度 116.3974，纬度 39.9093\n\n` +
                   `这个位置可以用于精确的路线规划！`;
        }
    }

    addUserMessage(message) {
        const chatMessages = document.getElementById('chat-messages');
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message user-message';
        messageDiv.innerHTML = `
            <div class="message-content">${message}</div>
        `;
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    addBotMessage(message) {
        const chatMessages = document.getElementById('chat-messages');
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message bot-message';
        messageDiv.innerHTML = `
            <div class="message-content">${message}</div>
        `;
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // 添加获取选项的函数
    async getSegmentOptions(type, origin, destination, date) {
        try {
            console.log(`获取${type}选项:`, { origin, destination, date });
            const response = await fetch(`${this.apiBaseUrl}/options`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    type: type,
                    origin: origin,
                    destination: destination,
                    date: date
                })
            });
            const data = await response.json();
            console.log('选项API响应:', data);
            return data.success ? data.options : [];
        } catch (error) {
            console.error('获取选项失败:', error);
            return [];
        }
    }

    // 创建下拉框HTML
    createDropdown(segment, options, routeIndex, segmentIndex) {
        if (!options || options.length <= 1) {
            return segment;
        }
        
        const dropdownId = `dropdown_${routeIndex}_${segmentIndex}`;
        const currentOption = options.find(opt => 
            opt.departure_time === segment.departure_time && 
            opt.arrival_time === segment.arrival_time
        ) || options[0];
        
        let dropdownHtml = `<div class="segment-dropdown">`;
        dropdownHtml += `<select id="${dropdownId}" onchange="travelOptimizer.updateSegmentPrice(${routeIndex}, ${segmentIndex}, this.value)">`;
        
        options.forEach(option => {
            const selected = option.id === currentOption.id ? 'selected' : '';
            dropdownHtml += `<option value="${option.id}" ${selected}>${option.display}</option>`;
        });
        
        dropdownHtml += `</select>`;
        dropdownHtml += `</div>`;
        
        return {
            ...segment,
            dropdownHtml: dropdownHtml,
            options: options,
            currentOption: currentOption
        };
    }

    // 更新段选项
    async updateSegmentOption(routeIndex, segmentIndex, segmentType, optionValue) {
        console.log(`更新路线${routeIndex}段${segmentIndex}的选项:`, segmentType, optionValue);
        
        if (optionValue === 'load-more') {
            // 加载更多选项
            await this.loadSegmentOptions(routeIndex, segmentIndex, segmentType);
        } else if (optionValue !== 'current') {
            // 更新为选中的选项
            await this.updateSegmentToOption(routeIndex, segmentIndex, segmentType, optionValue);
        }
    }
    
    // 加载段选项
    async loadSegmentOptions(routeIndex, segmentIndex, segmentType) {
        const routeCard = document.querySelector(`[data-route-id="route-${routeIndex}"]`);
        if (!routeCard) return;
        
        const stepElement = routeCard.querySelector(`.route-step:nth-child(${segmentIndex + 1})`);
        if (!stepElement) return;
        
        const dropdown = stepElement.querySelector('.segment-dropdown');
        if (!dropdown) return;
        
        // 获取当前段的信息
        const stepInfo = stepElement.querySelector('.step-route').textContent;
        const [origin, destination] = stepInfo.split(' → ');
        
        // 获取日期
        const dateInput = document.getElementById('departure-date');
        const date = dateInput ? dateInput.value : '';
        const optimizationSelect = document.getElementById('optimization-type');
        const prefer = optimizationSelect ? (optimizationSelect.value === 'price' ? 'price' : 'time') : 'time';
        const currentDeparture = (stepElement.querySelector('.step-time')?.textContent || '').match(/\d{2}:\d{2}/)?.[0] || '';
        
        try {
            // 显示加载状态
            dropdown.innerHTML = '<option>加载中...</option>';
            
            let options = [];
            if (segmentType === 'train') {
                // 使用后端窗口筛选高铁接口，起点用当前段的发车时间
                const resp = await fetch(`${this.apiBaseUrl}/rail_options`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        mid_city: origin,
                        destination: destination,
                        date: date,
                        earliest: currentDeparture,
                        window_minutes: 180,
                        max_options: 6
                    })
                });
                const data = await resp.json();
                const routes = (data && data.success && Array.isArray(data.options)) ? data.options : [];
                options = routes.map(r => {
                    const d = (r.details && r.details[0]) || {};
                    return {
                        id: `${d.train_number || ''}_${d.departure_time || ''}`,
                        display: `${d.train_number || ''} ${d.departure_time || ''}-${d.arrival_time || ''}`,
                        price: (typeof r.price === 'number' ? r.price : (typeof r.total_price === 'number' ? r.total_price : 0)),
                        departure_time: d.departure_time || '',
                        arrival_time: d.arrival_time || '',
                        train_number: d.train_number || '',
                        seat_type: d.seat_selected || '',
                    };
                });
            } else if (segmentType === 'ground') {
                const resp = await fetch(`${this.apiBaseUrl}/ground_options`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ origin, destination, prefer })
                });
                const data = await resp.json();
                const opts = (data && data.success && Array.isArray(data.options)) ? data.options : [];
                options = opts.map(o => ({
                    id: o.id,
                    display: o.display,
                    duration: o.duration,
                    price: o.price,
                    tolls: o.tolls,
                    type: o.type
                }));
            } else {
                options = await this.getSegmentOptions(segmentType, origin, destination, date);
            }
            
            // 更新下拉框
            dropdown.innerHTML = '';
            
            // 添加当前选择选项
            const currentOption = document.createElement('option');
            currentOption.value = 'current';
            currentOption.textContent = '当前选择';
            currentOption.selected = true;
            dropdown.appendChild(currentOption);
            
            // 添加所有可选选项
            options.forEach(option => {
                const optionElement = document.createElement('option');
                optionElement.value = option.id;
                optionElement.textContent = option.display;
                dropdown.appendChild(optionElement);
            });
            
            if (!options.length) {
                const none = document.createElement('option');
                none.value = 'none';
                none.textContent = '暂无更多选项';
                none.disabled = true;
                dropdown.appendChild(none);
            }
            
            console.log(`加载了${options.length}个${segmentType}选项`);
        } catch (error) {
            console.error('加载选项失败:', error);
            dropdown.innerHTML = '<option>加载失败</option>';
        }
    }
    
    // 更新段到指定选项
    async updateSegmentToOption(routeIndex, segmentIndex, segmentType, optionId) {
        console.log(`更新段到选项:`, optionId);
        try {
            const routeCard = document.querySelector(`[data-route-id="route-${routeIndex}"]`);
            if (!routeCard) return;
            const stepElement = routeCard.querySelector(`.route-step:nth-child(${segmentIndex + 1})`);
            if (!stepElement) return;

            // 解析当前段的起终点
            const stepInfoText = stepElement.querySelector('.step-route')?.textContent || '';
            const parts = stepInfoText.split(' → ');
            if (parts.length !== 2) return;
            const origin = parts[0];
            const destination = parts[1];

            // 日期
            const dateInput = document.getElementById('departure-date');
            const date = dateInput ? dateInput.value : '';
            const optimizationSelect = document.getElementById('optimization-type');
            const prefer = optimizationSelect ? (optimizationSelect.value === 'price' ? 'price' : 'time') : 'time';

            // 获取全部候选并定位所选项
            let picked = null;
            if (segmentType === 'train') {
                const currentDeparture = (stepElement.querySelector('.step-time')?.textContent || '').match(/\d{2}:\d{2}/)?.[0] || '';
                const resp = await fetch(`${this.apiBaseUrl}/rail_options`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        mid_city: origin,
                        destination: destination,
                        date: date,
                        earliest: currentDeparture,
                        window_minutes: 180,
                        max_options: 6
                    })
                });
                const data = await resp.json();
                const routes = (data && data.success && Array.isArray(data.options)) ? data.options : [];
                const options = routes.map(r => {
                    const d = (r.details && r.details[0]) || {};
                    return {
                        id: `${d.train_number || ''}_${d.departure_time || ''}`,
                        display: `${d.train_number || ''} ${d.departure_time || ''}-${d.arrival_time || ''}`,
                        price: (typeof r.price === 'number' ? r.price : (typeof r.total_price === 'number' ? r.total_price : 0)),
                        departure_time: d.departure_time || '',
                        arrival_time: d.arrival_time || '',
                        train_number: d.train_number || ''
                    };
                });
                picked = options.find(o => o.id === optionId) || null;
            } else if (segmentType === 'ground') {
                const resp = await fetch(`${this.apiBaseUrl}/ground_options`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ origin, destination, prefer })
                });
                const data = await resp.json();
                const options = (data && data.success && Array.isArray(data.options)) ? data.options : [];
                picked = options.find(o => o.id === optionId) || null;
            } else {
                const options = await this.getSegmentOptions(segmentType, origin, destination, date);
                picked = options.find(o => o.id === optionId) || null;
            }
            if (!picked) return;

            // 更新该段的时间与价格展示
            const timeDiv = stepElement.querySelector('.step-time');
            const priceSpan = stepElement.querySelector(`#price-route-${routeIndex}-step-${segmentIndex}`) || stepElement.querySelector('[id^="price-"]');
            if (timeDiv) {
                // 基础时间字符串
                let suffix = '';
                if (segmentType === 'flight') {
                    suffix = `${picked.airline ? ` | ${picked.airline}` : ''}${picked.flight_number ? ` · ${picked.flight_number}` : ''}`;
                } else if (segmentType === 'train') {
                    suffix = ` | 车次 ${picked.train_number || ''}`;
                } else if (segmentType === 'ground') {
                    // 展示地面出行类型与费用（优先price，其次tolls）
                    const usedPrice = (typeof picked.price === 'number' && picked.price > 0) ? picked.price : (typeof picked.tolls === 'number' && picked.tolls > 0) ? picked.tolls : 0;
                    const priceText = usedPrice > 0 ? `¥${usedPrice}` : '—';
                    timeDiv.innerHTML = `${picked.duration || ''}分钟 | <span id="price-route-${routeIndex}-step-${segmentIndex}">${priceText}</span>`;
                    // 把选中价格与时长记到DOM，便于汇总
                    stepElement.dataset.price = String(usedPrice || 0);
                    stepElement.dataset.duration = String(picked.duration || 0);
                    this.updateRouteTotals(routeCard);
                    return;
                }
                const priceText = (typeof picked.price === 'number' && picked.price > 0) ? `¥${picked.price}` : '待查价';
                timeDiv.innerHTML = `${picked.departure_time || ''} - ${picked.arrival_time || ''} | <span id="price-route-${routeIndex}-step-${segmentIndex}">${priceText}</span>${suffix}`;
                // 航班/高铁段：尝试从起止时刻计算分钟差
                try {
                    const d = (picked.departure_time || '').match(/(\d{2}):(\d{2})/);
                    const a = (picked.arrival_time || '').match(/(\d{2}):(\d{2})/);
                    if (d && a) {
                        const dm = parseInt(d[1],10)*60 + parseInt(d[2],10);
                        let am = parseInt(a[1],10)*60 + parseInt(a[2],10);
                        if (am < dm) am += 24*60; // 跨日
                        stepElement.dataset.duration = String(am - dm);
                    }
                } catch(_){}
            }

            // 轻量更新卡片副标题（不做全量总价/总时长重算，后续完善）
            const headerSub = routeCard.querySelector('.route-sub');
            if (headerSub && segmentType === 'train') {
                const old = headerSub.textContent || '';
                headerSub.textContent = old.replace(/\d{2}:\d{2}\s*-\s*\d{2}:\d{2}/, `${(picked.departure_time || '').slice(-5)} - ${(picked.arrival_time || '').slice(-5)}`);
            }

            // 汇总总价/总时间
            this.updateRouteTotals(routeCard);
        } catch (e) {
            console.error('更新段失败:', e);
        }
    }

    // 汇总当前卡片的总价与总时间（分钟），并更新右上角显示
    updateRouteTotals(routeCard) {
        if (!routeCard) return;
        const stepNodes = routeCard.querySelectorAll('.route-step');
        let totalPrice = 0;
        let totalMinutes = 0;
        stepNodes.forEach(step => {
            let p = 0; let m = 0;
            if (step.dataset && step.dataset.price) {
                p = parseInt(step.dataset.price || '0', 10) || 0;
            } else {
                // 从文案中解析价格 ¥xxx
                const t = step.querySelector('.step-time');
                if (t) {
                    const mm = t.textContent.match(/¥(\d+)/);
                    if (mm) p = parseInt(mm[1] || '0', 10) || 0;
                }
            }
            if (step.dataset && step.dataset.duration) {
                m = parseInt(step.dataset.duration || '0', 10) || 0;
            } else {
                const t = step.querySelector('.step-time');
                if (t) {
                    // 文案中有“xx分钟”
                    const dm = t.textContent.match(/(\d+)分/);
                    if (dm) m = parseInt(dm[1] || '0', 10) || 0;
                    // 或者有起止时刻，计算分钟差
                    if (!m) {
                        const times = t.textContent.match(/(\d{2}):(\d{2}).*(\d{2}):(\d{2})/);
                        if (times) {
                            const dm2 = parseInt(times[1],10)*60 + parseInt(times[2],10);
                            let am2 = parseInt(times[3],10)*60 + parseInt(times[4],10);
                            if (am2 < dm2) am2 += 24*60;
                            m = am2 - dm2;
                        }
                    }
                }
            }
            totalPrice += p;
            totalMinutes += m;
        });
        const priceSpanTop = routeCard.querySelector('.route-stats span:nth-child(2)');
        const timeSpanTop = routeCard.querySelector('.route-stats span:nth-child(1)');
        if (priceSpanTop) {
            if (totalPrice > 0) {
                priceSpanTop.textContent = `💰 ¥${totalPrice}`;
            } else {
                priceSpanTop.textContent = '💰 待查价';
            }
        }
        if (timeSpanTop) {
            if (totalMinutes > 0) {
                const h = Math.floor(totalMinutes / 60);
                const m = totalMinutes % 60;
                const txt = h > 0 ? `${h}小时${m}分钟` : `${m}分钟`;
                timeSpanTop.textContent = `⏱ ${txt}`;
            }
        }
    }

    displayRoutes(routes) {
        const resultsSection = document.getElementById('results-section');
        const routesContainer = document.getElementById('routes-container');

        // 获取当前优化类型
        const optimizationSelect = document.getElementById('optimization-type');
        const optimizationType = optimizationSelect ? optimizationSelect.value : 'time';

        // 统一取值函数（兼容 price/total_price 与 total_time）
        const getPrice = (r) => (typeof r.total_price === 'number' ? r.total_price : (typeof r.price === 'number' ? r.price : 0));
        const getTime = (r) => (typeof r.total_time === 'number' ? r.total_time : 0);

        // 使用后端已排好序的顺序
        const sorted = [...routes];
 
        if (sorted.length === 0) {
            routesContainer.innerHTML = '<p style="text-align: center; color: #718096;">没有找到合适的路线</p>';
        } else {
            // 生成总结信息（基于排序后的第一条）
            const best = sorted[0];
            const bestFirst = best && best.details && best.details[0] ? best.details[0] : {};
            const formatPrice = (r, alt='') => {
                if (r && r.sold_out) return '无票';
                const priceVal = (r && (typeof r.total_price === 'number' ? r.total_price : (typeof r.price === 'number' ? r.price : undefined)));
                if (typeof priceVal === 'number' && priceVal > 0) {
                    const prefix = r && r.approx_price ? '约 ' : '';
                    return `${prefix}¥${priceVal}`;
                }
                return '待查价';
            };

            const bestSummary = `
                <div style="margin:0 0 12px 0;padding:12px 14px;background:#f7fafc;border:1px solid #e2e8f0;border-radius:8px;color:#2d3748;">
                    <strong>当前最优方案（${optimizationType === 'price' ? '价格最低' : optimizationType === 'composite' ? '综合效用最高' : '用时最短'}）：</strong>
                    ${bestFirst.airline ? bestFirst.airline + ' · ' : ''}${bestFirst.flight_number || ''}
                    ｜ ${bestFirst.departure_time || ''}-${bestFirst.arrival_time || ''}
                    ｜ ⏱️ ${getTime(best)}小时 ｜ 💰 ${formatPrice(best)}
                </div>
            `;

            // 分组渲染（按后端已排序好的 category 顺序：直达→日内到达→隔日到达→其他），并支持折叠
            let html = bestSummary;
            let currentCategory = null;
            const unknownTasks = [];
            const dateInput = document.getElementById('departure-date');
            const departureDate = dateInput ? dateInput.value : '';

            const closeGroup = () => { html += currentCategory ? '</div>' : ''; };

            sorted.forEach((route, index) => {
                if (route.category !== currentCategory) {
                    // 关闭上一个分组容器
                    if (currentCategory !== null) {
                        closeGroup();
                    }
                    // 开启新分组
                    const groupTitle = route.category || '其他';
                    html += `<div class="group-header" style="cursor:pointer;user-select:none;display:flex;align-items:center;gap:8px;">
                                <span style="font-weight:600;">${groupTitle}</span>
                                <span class="group-toggle" style="font-size:12px;color:#4a5568;">点击折叠/展开</span>
                             </div>`;
                    html += `<div class="group-container" data-category="${groupTitle}">`;
                    currentCategory = route.category;
                }

                const badgeText = route.badge || route.arrival_label || '';

                const detailType = (route.details && route.details[0]?.type) || '';
                const isTrain = route.type === 'high_speed_rail' || detailType === 'high_speed_rail';
                const isFlight = route.type === 'flight' || detailType === 'flight';

                let subLine = '';
                if (isTrain) {
                    const dep = (route.details && route.details[0]?.departure_time) || (route.dep_time?.split(' ')[1] || '');
                    const arr = (route.details && route.details[0]?.arrival_time) || (route.arr_time?.split(' ')[1] || '');
                    const trainCode = route.train_code || route.train_number || (route.details && route.details[0]?.train_number) || '';
                    const seat = route.sold_out ? '无票' : (route.seat_selected || (route.details && route.details[0]?.seat_selected) || '');
                    const seatLeftVal = route.sold_out ? '' : (route.seat_left || (route.details && route.details[0]?.seat_left) || '');
                    const seatLeft = seatLeftVal ? `（${seatLeftVal}）` : '';
                    const priceText = formatPrice(route);
                    subLine = `${dep} - ${arr} ｜ ${priceText} ｜ 车次 ${trainCode} · ${seat}${seatLeft}`;
                } else if (isFlight) {
                    const dep = route.dep_time?.split(' ')[1] || (route.details && route.details[0]?.departure_time) || '';
                    const arr = route.arr_time?.split(' ')[1] || (route.details && route.details[0]?.arrival_time) || '';
                    const priceText = formatPrice(route);
                    const fn = (route.details && route.details[0]?.flight_number) || route.flight_number || '';
                    const airline = (route.details && route.details[0]?.airline) || route.airline || '';
                    subLine = `${dep} - ${arr} ｜ ${priceText} ｜ ${airline} · ${fn}`;
                }

                const cardId = `route-${index}`;
                const displayIndex = route.category_index || (index + 1);

                // 方案卡片
                html += `
                    <div class="route-card" data-route-id="${cardId}">
                        <div class="route-header">
                            <div class="route-title">方案 ${displayIndex}
                                ${badgeText ? `<span class="badge">${badgeText}</span>` : ''}
                            </div>
                            ${subLine ? `<div class="route-sub">${subLine}</div>` : ''}
                            <div class="route-stats">
                                <span>⏱️ ${getTime(route)}小时</span>
                                <span>💰 ${formatPrice(route)}</span>
                                <span>🔄 ${route.transfers}次换乘</span>
                            </div>
                        </div>
                        <div class="route-details">
                            ${route.details.map((step, sidx) => {
                                const stepId = `${cardId}-step-${sidx}`;
                                const stepPriceText = formatPrice(step, '—');
                                const isStepTrain = step.type === 'high_speed_rail';
                                const isStepFlight = step.type === 'flight';
                                const isStepGround = step.type === 'ground_transport';
                                const needFetch = isStepTrain && !route.sold_out && ((step.price_source === 'unknown') || (!(typeof step.price === 'number' && step.price > 0)));
                                if (needFetch) {
                                    unknownTasks.push({
                                        priceSpanId: `price-${stepId}`,
                                        payload: {
                                            date: departureDate,
                                            train_no: step.train_no || '',
                                            from_station_no: step.from_station_no || '',
                                            to_station_no: step.to_station_no || '',
                                            seat_types: step.seat_types || '',
                                            seat_label: step.seat_selected || ''
                                        }
                                    });
                                }
                                
                                // 仅在联运方案下对高铁段和地面段显示下拉框
                                let dropdownHtml = '';
                                const isMulti = (typeof route.transfers === 'number' && route.transfers > 0);
                                if (isMulti && (isStepTrain || isStepGround)) {
                                    const segmentType = isStepTrain ? 'train' : 'ground';
                                    dropdownHtml = `
                                        <div class="segment-dropdown-container">
                                            <select class="segment-dropdown" onchange="travelOptimizer.updateSegmentOption(${index}, ${sidx}, '${segmentType}', this.value)">
                                                <option value="current" selected>当前选择</option>
                                                <option value="load-more">加载更多选项...</option>
                                            </select>
                                        </div>
                                    `;
                                }
                                
                                return `
                                <div class="route-step">
                                    <div class="transport-icon ${this.getTransportClass(step.type)}">
                                        ${this.getTransportIcon(step.type)}
                                    </div>
                                    <div class="step-info">
                                        <div class="step-route">${step.origin} → ${step.destination}</div>
                                        <div class="step-time-container">
                                            <div class="step-time">
                                                ${step.departure_time} - ${step.arrival_time} | <span id="price-${stepId}">${stepPriceText}</span>
                                                ${
                                                    step.type === 'high_speed_rail'
                                                        ? (() => {
                                                            const trainCode = step.train_number || route.train_number || route.train_code || '';
                                                            const seat = route.sold_out ? '无票' : (step.seat_selected || route.seat_selected || '');
                                                            const seatLeftVal = route.sold_out ? '' : ((step.seat_left || route.seat_left) || '');
                                                            const seatLeft = seatLeftVal ? `（${seatLeftVal}）` : '';
                                                            return ` | 车次 ${trainCode} · ${seat}${seatLeft}`;
                                                        })()
                                                        : step.type === 'ground_transport'
                                                        ? (() => {
                                                            const transportType = step.transport_type || 'driving';
                                                            const duration = step.duration || 0;
                                                            const distance = step.distance || 0;
                                                            const typeText = transportType === 'driving' ? '驾车' : transportType === 'transit' ? '公交' : transportType === 'subway' ? '地铁' : '出行';
                                                            return ` | ${typeText}${duration ? `约${duration}分钟` : ''}${distance ? `，${distance}公里` : ''}`;
                                                        })()
                                                        : `${step.airline ? ` | ${step.airline}` : ''}${step.flight_number ? ` · ${step.flight_number}` : ''}`
                                                }
                                            </div>
                                            ${dropdownHtml}
                                        </div>
                                    </div>
                                </div>`;
                            }).join('')}
                        </div>
                    </div>
                `;
            });

            // 关闭最后一个分组
            if (currentCategory !== null) {
                closeGroup();
            }

            routesContainer.innerHTML = html;

            // 组头折叠/展开事件
            document.querySelectorAll('.group-header').forEach(h => {
                h.addEventListener('click', () => {
                    const cont = h.nextElementSibling;
                    if (!cont) return;
                    const isHidden = cont.style.display === 'none';
                    cont.style.display = isHidden ? 'block' : 'none';
                });
            });

            // 渲染后对未知价的高铁段按需补价
            if (unknownTasks.length) {
                unknownTasks.forEach(task => {
                    try {
                        fetch(`${this.apiBaseUrl}/rail_price`, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(task.payload)
                        }).then(r => r.json()).then(data => {
                            const span = document.getElementById(task.priceSpanId);
                            if (!span) return;
                            if (data && data.success && data.seat_price > 0) {
                                span.textContent = `¥${data.seat_price}`;
                            }
                        }).catch(() => {});
                    } catch (_) {}
                });
            }
        }

        resultsSection.style.display = 'block';
        resultsSection.scrollIntoView({ behavior: 'smooth' });
    }

    getTransportClass(type) {
        const classMap = {
            'high_speed_rail': 'high-speed-rail',
            'flight': 'flight',
            'bus': 'bus',
            'ground_transport': 'ground-transport'
        };
        return classMap[type] || 'bus';
    }

    getTransportIcon(type) {
        const iconMap = {
            'high_speed_rail': '🚄',
            'flight': '✈️',
            'bus': '🚌',
            'ground_transport': '🚗'
        };
        return iconMap[type] || '🚌';
    }

    showLoading(show) {
        const loading = document.getElementById('loading');
        loading.style.display = show ? 'flex' : 'none';
    }

    showError(message) {
        // 创建错误提示模态框
        const modal = document.createElement('div');
        modal.className = 'error-modal';
        modal.innerHTML = `
            <div class="error-content">
                <h3>❌ 搜索失败</h3>
                <p>${message}</p>
                <button onclick="this.parentElement.parentElement.remove()">确定</button>
            </div>
        `;
        
        // 添加样式
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        `;
        
        document.body.appendChild(modal);
        
        // 3秒后自动关闭
        setTimeout(() => {
            if (modal.parentElement) {
                modal.remove();
            }
        }, 5000);
    }

    // 移除了复杂的独立功能方法
    // 现在所有功能都通过AI对话智能处理

    // 智能地点搜索（集成高德POI搜索）
    async searchPlaces(query, suggestions, input) {
        try {
            // 首先尝试高德地图POI搜索
            const poiResults = await this.searchPOIWithAmap(query);
            if (Array.isArray(poiResults) && poiResults.length > 0) {
                this.showSuggestions(suggestions, poiResults, input);
                return;
            }
        } catch (error) {
            console.log('高德POI搜索失败，使用本地城市数据');
        }
        
        // 如果高德搜索失败，使用本地城市数据
        const q = String(query || '').toLowerCase().trim();
        const cities = Array.isArray(this.cities) ? this.cities : [];
        const matches = cities.filter(city => {
            const n = (city && (city.name || city.full_name) || '').toLowerCase();
            return q && n.includes(q);
        }).slice(0, 10);
        
        this.showSuggestions(suggestions, matches, input);
    }

    async searchPOIWithAmap(query) {
        try {
            const response = await fetch(`${this.apiBaseUrl}/poi`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    keyword: query,
                    city: '',
                    types: '010000|020000|030000|040000|050000|060000|070000|080000|090000|100000|110000|120000|130000|140000|150000|160000|170000|180000|190000|200000'
                })
            });
            if (!response.ok) {
                return [];
            }
            const data = await response.json();
            if (data.success && data.pois) {
                return data.pois.map(poi => ({
                    name: poi.name,
                    address: poi.address,
                    location: poi.location,
                    type: poi.type,
                    level: 'poi',
                    code: poi.id,
                    full_name: poi.name + (poi.address ? ' - ' + poi.address : '')
                }));
            }
        } catch (error) {
            console.error('POI搜索错误:', error);
        }
        
        return [];
    }

    // 地图相关方法
    initMap() {
        if (typeof AMap === 'undefined') {
            console.error('高德地图API未加载');
            return;
        }

        this.map = new AMap.Map('mapContainer', {
            zoom: 10,
            center: [116.3974, 39.9093], // 北京
            mapStyle: 'amap://styles/normal'
        });

        // 添加地图控件
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.ToolBar());

        // 获取当前位置
        this.getCurrentLocation();
    }

    getCurrentLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const lng = position.coords.longitude;
                    const lat = position.coords.latitude;
                    this.currentLocation = [lng, lat];

                    // 添加当前位置标记
                    const marker = new AMap.Marker({
                        position: [lng, lat],
                        title: '我的位置',
                        icon: new AMap.Icon({
                            size: new AMap.Size(32, 32),
                            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
                        })
                    });
                    this.map.add(marker);
                    this.map.setCenter([lng, lat]);

                    // 逆地理编码获取地址
                    const geocoder = new AMap.Geocoder();
                    geocoder.getAddress([lng, lat], (status, result) => {
                        if (status === 'complete' && result.regeocode) {
                            const address = result.regeocode.formattedAddress;
                            document.getElementById('origin').value = address;
                        }
                    });
                },
                (error) => {
                    console.error('获取位置失败:', error);
                    console.log('无法获取您的位置，请手动输入出发地');
                }
            );
        } else {
            console.log('您的浏览器不支持地理定位');
        }
    }

    clearRoute() {
        if (this.routeLayer) {
            this.map.remove(this.routeLayer);
            this.routeLayer = null;
        }
        if (this.flightPolyline) {
            this.map.remove(this.flightPolyline);
            this.flightPolyline = null;
        }
        if (this._routeMarkers && this._routeMarkers.length) {
            this.map.remove(this._routeMarkers);
            this._routeMarkers = [];
        }
    }

    // 在地图上显示路线
    displayRouteOnMap(origin, destination) {
        if (!this.map) return;

        // 清除之前的路线
        this.clearRoute();

        const toLngLat = (loc) => {
            try {
                if (!loc) return null;
                if (loc instanceof AMap.LngLat) return loc;
                if (Array.isArray(loc) && loc.length >= 2) return new AMap.LngLat(Number(loc[0]), Number(loc[1]));
                if (typeof loc === 'object' && 'lng' in loc && 'lat' in loc) return new AMap.LngLat(Number(loc.lng), Number(loc.lat));
                if (typeof loc === 'string' && loc.includes(',')) {
                    const [lng, lat] = loc.split(',');
                    return new AMap.LngLat(Number(lng), Number(lat));
                }
            } catch (e) { console.warn('toLngLat parse error', e, loc); }
            return null;
        };

        // 地理编码
        const geocoder = new AMap.Geocoder();
        geocoder.getLocation(origin, (status, result) => {
            if (status === 'complete' && result.geocodes.length > 0) {
                const originPos = toLngLat(result.geocodes[0].location);

                geocoder.getLocation(destination, (status, result) => {
                    if (status === 'complete' && result.geocodes.length > 0) {
                        const destPos = toLngLat(result.geocodes[0].location);

                        // 对于航班，画一条大圆/直线示意
                        try {
                            // 起终点标记
                            const startMarker = new AMap.Marker({ position: originPos, title: '出发地', offset: new AMap.Pixel(-10, -10) });
                            const endMarker = new AMap.Marker({ position: destPos, title: '目的地', offset: new AMap.Pixel(-10, -10) });
                            this._routeMarkers = [startMarker, endMarker];
                            this.map.add(this._routeMarkers);
                            this.flightPolyline = new AMap.Polyline({
                                path: [originPos, destPos],
                                strokeColor: '#e53e3e',
                                strokeWeight: 6,
                                strokeOpacity: 0.9,
                                showDir: true
                            });
                            this.map.add(this.flightPolyline);
                            this.map.setFitView([startMarker, endMarker, this.flightPolyline]);
                        } catch (e) {}

                        // 同时提供驾车路线按钮效果（如有需要可启用）
                        this.planRoute(originPos, destPos);
                    } else {
                        console.log('无法找到目的地位置');
                    }
                });
            } else {
                console.log('无法找到出发地位置');
            }
        });
    }

    planRoute(origin, destination) {
        const driving = new AMap.Driving({
            map: this.map,
            showTraffic: true,
            hideMarkers: false
        });

        driving.search(origin, destination, (status, result) => {
            if (status === 'complete') {
                this.routeLayer = driving;
                console.log('路线规划完成');
                
                // 显示路线信息面板
                this.showRouteInfo(result);
            } else {
                console.log('路线规划失败');
            }
        });
    }

    showRouteInfo(result) {
        const panel = document.getElementById('route-info-panel');
        const details = document.getElementById('route-details');
        
        if (result.routes && result.routes.length > 0) {
            const route = result.routes[0];
            let html = `
                <div class="route-summary">
                    <div class="route-item">
                        <span class="label">总距离:</span>
                        <span class="value">${(route.distance / 1000).toFixed(1)}公里</span>
                    </div>
                    <div class="route-item">
                        <span class="label">预计时间:</span>
                        <span class="value">${Math.round(route.time / 60)}分钟</span>
                    </div>
                    <div class="route-item">
                        <span class="label">过路费:</span>
                        <span class="value">${route.tolls || '无'}</span>
                    </div>
                </div>
            `;
            details.innerHTML = html;
            panel.style.display = 'block';
        }
    }
}

// 全局函数，供HTML调用
function getCurrentLocation() {
    if (window.travelOptimizer) {
        window.travelOptimizer.getCurrentLocation();
    }
}

function clearRoute() {
    if (window.travelOptimizer) {
        window.travelOptimizer.clearRoute();
    }
}

function toggleTraffic() {
    if (window.travelOptimizer && window.travelOptimizer.map) {
        // 切换路况显示
        const trafficLayer = window.travelOptimizer.trafficLayer;
        if (trafficLayer) {
            window.travelOptimizer.map.remove(trafficLayer);
            window.travelOptimizer.trafficLayer = null;
        } else {
            window.travelOptimizer.trafficLayer = new AMap.TileLayer.Traffic({
                zIndex: 10
            });
            window.travelOptimizer.map.add(window.travelOptimizer.trafficLayer);
        }
    }
}

// AI快捷功能
function askWeather() {
    const input = document.getElementById('user-input');
    input.value = '查询天气';
    input.focus();
}

function askPoi() {
    const input = document.getElementById('user-input');
    input.value = '搜索附近';
    input.focus();
}

function askLocation() {
    const input = document.getElementById('user-input');
    input.value = '定位地址';
    input.focus();
}

function askRoute() {
    const input = document.getElementById('user-input');
    input.value = '规划路线';
    input.focus();
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.travelOptimizer = new TravelOptimizer();
});